package cn.wolfcode.wms.web.controller;

import cn.wolfcode.wms.domain.Employee;
import cn.wolfcode.wms.query.EmployeeQueryObject;
import cn.wolfcode.wms.service.IDepartmentService;
import cn.wolfcode.wms.service.IEmployeeService;
import cn.wolfcode.wms.service.IRoleService;
import cn.wolfcode.wms.utils.JsonResult;
import cn.wolfcode.wms.utils.RequirePermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService service;
    @Autowired
    private IDepartmentService deptService;
    @Autowired
    private IRoleService roleService;
    @RequestMapping("list")
    @RequirePermission("员工的列表")
    public String list(Model model, @ModelAttribute("qo") EmployeeQueryObject qo){
        model.addAttribute("dept",deptService.selectAll());
        model.addAttribute("result", service.query(qo));
        return "employee/list";
    }

    @RequestMapping("delete")
    @ResponseBody
    @RequirePermission("员工的删除")
    public JsonResult delete(Long id){
        JsonResult result = new JsonResult();
        try{
            if(id != null){
                service.deleteByPrimaryKey(id);
            }

        }catch (Exception e){
            e.printStackTrace();
            result.mark("删除失败!");
        }

        return result;
    }
    //批量删除
    @RequestMapping("batchDelete")
    @ResponseBody
    @RequirePermission("员工的批量删除")
    public JsonResult batchDelete(Long[] ids){
        JsonResult result = new JsonResult();
        try{
            if(ids != null){
                service.batchDelete(ids);
            }

        }catch (Exception e){
            e.printStackTrace();
            result.mark("删除失败!");
        }

        return result;
    }

    @RequestMapping("input")
    @RequirePermission("员工编辑")
    public String input(Long id,Model model){
        model.addAttribute("dept",deptService.selectAll());
        model.addAttribute("roles",roleService.selectAll());
        if(id!=null){
            Employee emp = service.selectByPrimaryKey(id);
            model.addAttribute("emp",emp);
        }

        return "employee/input";
    }
    @RequestMapping("saveOrUpdate")
    @RequirePermission("员工保存和更新")
    public String saveOrUpdate(Employee employee,Long[] roleIds){
        if(employee.getId()!=null){
            service.updateByPrimaryKey(employee,roleIds);

        }else {
            service.insert(employee,roleIds);
        }

        return "redirect:/employee/list.do";
    }
}
